package com.xingkeduo.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xingkeduo.configuration.websocket.WebsocketMessageResponse;
import com.xingkeduo.dao.workpad.TStoreStaffMapper;
import com.xingkeduo.model.po.TShops;
import com.xingkeduo.model.po.TStaffAttendance;
import com.xingkeduo.model.po.TStoreStaff;
import com.xingkeduo.model.vo.StaffInfoVo;
import com.xingkeduo.model.vo.StoreStaffVo;
import com.xingkeduo.send.RabbitMqSender;
import com.xingkeduo.service.*;
import com.xingkeduo.util.TimeUtil;
import com.xingkeduo.util.tool.ResponseMessage;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.xingkeduo.configuration.websocket.WebsocketMessageResponse.MessageTypeEnum.WORKPAD;

/**
 * @Author: 中文输入法发挥不稳定的刘川
 * @Date: 19-3-13 下午3:29
 */
@Service
public class StoreStaffServiceImpl implements StoreStaffService {

    private static Logger log = LoggerFactory.getLogger(StoreStaffServiceImpl.class);

    @Autowired
    TStoreStaffMapper storeStaffMapper;
    @Autowired
    ShopService shopService;
    @Autowired
    StaffAttendanceService staffAttendanceService;

    //服务间调用
    @Autowired
    BusinessuserFeignService businessuserFeignService;
    //服务间调用
    @Autowired
    OtherService otherService;

    //中间件
    @Autowired
    private RabbitMqSender rabbitMqSender;

    /**
     * 根据店铺信息 绑定员工和店铺
     *
     * @return boolean
     * @author 中文输入法发挥不稳定的刘川
     * @date 19-3-13 下午4:57
     */
    @Override
    public boolean bindStaffFromStoreInfo() {

        boolean complete = false;

        Date today = new Date();
        List<TStoreStaff> bindInsertList = new ArrayList<>();
        List<TStaffAttendance> attendanceList = new ArrayList<>();
        List<TShops> shops = shopService.getEnableShopIdAndNameList();

        for (TShops shop : shops) {
            Long storeId = shop.getId();
            //TODO 通过店铺id获取其下绑定员工列表
            List<Long> staffIdList = new ArrayList<>();
            for (Long oneStaffId : staffIdList) {
                Long staffId = oneStaffId;
                TStoreStaff bindRelative = new TStoreStaff();
                bindRelative.setCreator(0L);
                bindRelative.setEnable(true);
                bindRelative.setStaffId(staffId);
                bindRelative.setStoreId(storeId);
                //获取下下周一的日期
                Date dateOfNextAfterNextMonday = TimeUtil.getDateOfMonday(today, 2);
                Date dateOfNextMonday = TimeUtil.getDateOfMonday(today, 1);
                bindRelative.setWeekStartDate(dateOfNextAfterNextMonday);
                bindInsertList.add(bindRelative);
                //生成考勤
                    attendanceList.addAll(staffAttendanceService.initOneAttendance(staffId, "", storeId, "", 0L, dateOfNextAfterNextMonday));
                //TODO 循环结束
            }
        }

        //绑定信息插入
        int bindRowNum = storeStaffMapper.batchInsertForInit(bindInsertList);
        //自动生成的考勤
        int attendanceRowNum = staffAttendanceService.batchInsertForInit(attendanceList);

        if (bindRowNum > 0 && attendanceRowNum > 0) {
            complete = true;
        }
        return complete;
//        //TODO 获取店铺信息 与之相关的发型师信息 接口
//        Map<Long,List> infoMap =new HashMap<>();
//        //TODO 经各种解析 获取店铺id 员工id
//        infoMap.forEach((key,value)->{
//            Long storeId= key;
//
//            //TODO 循环员工列表
//            Long staffId= 1111L;
//            TStoreStaff bindRelative=new TStoreStaff();
//            bindRelative.setCreator(0L);
//            bindRelative.setEnable(true);
//            bindRelative.setStaffId(staffId);
//            bindRelative.setStoreId(storeId);
//            //获取下下周一的日期
//            Date dateOfNextAfterNextMonday = TimeUtil.getDateOfMonday(today,2);
//            Date dateOfNextMonday= TimeUtil.getDateOfMonday(today,1);
//            bindRelative.setWeekStartDate(dateOfNextAfterNextMonday);
//            bindInsertList.add(bindRelative);
//            //生成考勤
//            for (int i=0;i<6;i++){
//                TStaffAttendance attendance=new TStaffAttendance();
//                attendance.setCreator(0);
//                attendance.setEnable(true);
//                attendance.setStaffId(staffId);
//                attendance.setStoreId(storeId);
//                attendance.setManagerId(0L);
//                Calendar cal=Calendar.getInstance();
//                cal.setTime(dateOfNextAfterNextMonday);
//                cal.add(Calendar.DATE,i);
//                attendance.setDate(cal.getTime());
//                attendance.setStatus(false);
//                attendanceList.add(attendance);
//                //TODO 生成库存 返回List
//
//            }
//            //TODO 循环结束
//
//        });

    }

    @Override
    public Boolean bingStaffToStoreForWeek(Long staffId, String staffName, Long storeId, String storeName, Long creator, Date selectDate) {
        TStoreStaff bindRelative = new TStoreStaff();
        bindRelative.setCreator(creator);
        bindRelative.setEnable(true);
        bindRelative.setStaffId(staffId);
        bindRelative.setStaffName(staffName);
        bindRelative.setStoreId(storeId);
        bindRelative.setStoreName(storeName);
        Date thisWeekMondayDate = TimeUtil.getDateOfMonday(selectDate, 0);
        bindRelative.setWeekStartDate(thisWeekMondayDate);
        int rowNum = storeStaffMapper.insert(bindRelative);
        int res = 0;
        if (rowNum > 0) {
            res = staffAttendanceService.initAttendanceForOneStaff(staffId, staffName, storeId, storeName, creator, thisWeekMondayDate);
        }
        return res > 0;
    }


    /**
     * @return java.util.List<com.xingkeduo.model.po.TStoreStaff>
     * @description 根据店铺ID获取店铺下所有发型师
     * @Author 情绪极其不稳定的Shadow
     * @Param [storeId]
     **/
    @Override
    public List<StoreStaffVo> getStoreStaffList(Long storeId) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date dateOfMonday = TimeUtil.getDateOfMonday(new Date(), 0);
        List<TStoreStaff> storeStaffList = storeStaffMapper.getStoreStaffList(storeId, format.format(dateOfMonday));
        if(CollectionUtils.isEmpty(storeStaffList)){
            return null;
        }
        //准备数据
        List<Long> staffIds = new ArrayList<>();
        for (TStoreStaff storeStaff : storeStaffList) {
            staffIds.add(storeStaff.getStaffId());
        }
        Set setStaffId = new HashSet(staffIds);
        List staffIdList = new ArrayList(setStaffId);
        //从其他服务获取数据
        log.info("请求user系统参数："+staffIdList.toString());
        List<StaffInfoVo> staffInfoVoList = otherService.getStaffInfoVo(staffIdList);
        log.info("请求user系统结果size："+staffInfoVoList.size());
        List<StoreStaffVo> storeStaffVos = new ArrayList<>();
        for (TStoreStaff storeStaff : storeStaffList) {
            for (StaffInfoVo staffInfoVo : staffInfoVoList) {
                if (storeStaff.getStaffId().equals(staffInfoVo.getJobseekerId())) {
                	if(StringUtils.isNotEmpty(staffInfoVo.getName())) {
                		storeStaff.setStaffName(staffInfoVo.getName());//pantong添加  发型师真实姓名以staffInfoVoList的为准
                	}
                    StoreStaffVo storeStaffVo = new StoreStaffVo(storeStaff, staffInfoVo.getPath(), staffInfoVo.getCraftsName(), staffInfoVo.getCode());
                    storeStaffVos.add(storeStaffVo);
                }
            }
        }

        return storeStaffVos;
    }

    /**
     * @return java.util.List<com.xingkeduo.model.po.TStoreStaff>
     * @description 新增人员前查询是否已经存在该发型师
     * @Author 情绪极其不稳定的Shadow
     * @Param [selectDate, id, storeId, staffName, creator]
     **/
    @Override
    public TStoreStaff getStaffToStoreForWeek(Date selectDate, Long staffId, Long storeId) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(selectDate);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        Date thisWeekMondayDate = TimeUtil.getDateOfMonday(cal.getTime(), 0);
        log.info("查询当前绑定关系时传入时间格式："+ thisWeekMondayDate);
        TStoreStaff storeStaff = storeStaffMapper.selectByDateAndStoreId(thisWeekMondayDate, staffId, storeId);
        return storeStaff;
    }

    /**
     * 解绑人员与店铺关系
     * 查出解绑前人员信息,获取id，并通过
     *
     * @param bindIdList
     * @param managerId
     * @return java.lang.Boolean
     * @author 中文输入法发挥不稳定的刘川
     * @date 19-4-23 下午3:53
     */
    @Override
    public ResponseMessage unbindStoreStaff(List<Long> bindIdList, Long managerId) {
        log.info("当前需要解除的Id为："+bindIdList.toString());
        List<TStoreStaff> bindRelative = storeStaffMapper.selectByPrimaryKeyList(bindIdList);
        if (null == bindRelative||bindRelative.size()==0||bindIdList.size()!=bindRelative.size()) {
            return ResponseMessage.error("当前绑定关系不存在，或者已解除,尝试刷新页面");
        }
        int bindRows = storeStaffMapper.batchUnableStoreStaffBindRelative(bindIdList, managerId);
        ResponseMessage finalResponseMessage = ResponseMessage.ok();
        Long storeId = bindRelative.get(0).getStoreId();
        Date weekDay = bindRelative.get(0).getWeekStartDate();
        if (bindRows > 0) {
            for (TStoreStaff storeStaff : bindRelative) {
                Long staffId = storeStaff.getStaffId();
                ResponseMessage responseMessage = staffAttendanceService.unableStaffAttendanceByStoreIdAndStaffIdAndWeek(storeId, staffId, weekDay);
                if (responseMessage.getCode() != 200) {
                    finalResponseMessage.setCode(500);
                }
                finalResponseMessage.setmsg(finalResponseMessage.getMsg() + " " + responseMessage.getMsg());
            }
            rabbitMqSender.sendMessage("websocket_transfer_exchange", "websocket_transfer_key", JSON.toJSONString(new WebsocketMessageResponse<>(WORKPAD, String.valueOf(storeId), null)));
            return finalResponseMessage;
        } else {
            return ResponseMessage.error("解绑失败", 500);
        }
    }

    @Override
    public List<StoreStaffVo> getbindStoreStaffByDate(Long storeId, String selectDate) {
        Date dateOfMonday = TimeUtil.getDateOfMonday(selectDate, 0);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        List<StoreStaffVo> voList = new ArrayList<>();

        List<TStoreStaff> storeStaffs = storeStaffMapper.getbindStoreStaffByDate(storeId, format.format(dateOfMonday));
        if(CollectionUtils.isEmpty(storeStaffs)){
            return voList;
        }
        //准备数据
        List<Long> staffIds = new ArrayList<>();
        for(TStoreStaff storeStaff : storeStaffs){
            staffIds.add(storeStaff.getStaffId());
        }
        Set setStaffId = new HashSet(staffIds);
        List<Long> staffIdList = new ArrayList<>(setStaffId);
        List<StaffInfoVo> staffInfoVoList = otherService.getStaffInfoVo(staffIdList);
        if(CollectionUtils.isEmpty(staffInfoVoList)){
            return voList;
        }
        for(TStoreStaff storeStaff : storeStaffs){
            for(StaffInfoVo staffInfoVo : staffInfoVoList){
                if(staffInfoVo.getJobseekerId().equals(storeStaff.getStaffId())){
                    StoreStaffVo storeStaffVo = new StoreStaffVo(storeStaff, null, null, staffInfoVo.getCode());
                    voList.add(storeStaffVo);
                }
            }
        }
        return voList;
    }
}
